package com.dxy.yzs.marathon.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dxy.yzs.marathon.common.R;
import com.dxy.yzs.marathon.common.exception.util.DateUtil;
import com.dxy.yzs.marathon.common.log.annotation.LogAnnotation;
import com.dxy.yzs.marathon.domain.Label;
import com.dxy.yzs.marathon.domain.Post;
import com.dxy.yzs.marathon.service.LabelService;
import com.dxy.yzs.marathon.service.PostService;
import com.dxy.yzs.marathon.service.TopicService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * class description
 *
 * @author zhangxunwei
 * @date 2021/10/22
 */
@RestController
@RequestMapping("/index")
@AllArgsConstructor
public class IndexController {
    private final TopicService topicService;
    private final PostService postService;
    private final LabelService labelService;

    @LogAnnotation(module = "index")
    @GetMapping("/search")
    public R search(String text) {
        List<Map> postList = postService.search(text).stream().map(po -> {
            Map<String, Object> map = BeanUtil.beanToMap(po);
            Integer replyTimes = (Integer) map.get("replyTimes");
            Date createTime = (Date) map.get("createTime");
            String createTimeStr = DateUtil.showDate(createTime);
            map.put("createTime", createTimeStr);
            map.put("viewTimes", replyTimes * (Math.max(new Random().nextInt(100), 50)) + new Random().nextInt(40));
            return map;
        }).collect(Collectors.toList());
        List<Label> labelList = labelService.search(text);

        Map<String, Object> data = new HashMap<>(3);
        data.put("labelList", labelList);
        data.put("postList", postList);

        return R.ok().put("data", data);
    }

    @LogAnnotation(module = "index")
    @GetMapping("/topHot")
    public R topHot() {
        return R.ok().put("data", topicService.hotTop5());
    }

    @GetMapping("/hotDetail")
    public R hotDetail(Integer id) {
        return R.ok().put("data", postService.detail(id));
    }
}
